import json
import numpy as np
import os


def read_json(base_path, length, width, times=24):
    # base_path = './bock_count_json'
    file_list = os.listdir(base_path)
    days = len(file_list)
    all_data = np.zeros((length, width, times * days))
    count_data = np.zeros((length, width))

    for j in range(len(file_list)):

        path = base_path + '/' + file_list[j]
        with open(path) as f:
            load_dict = json.load(f)
            str0 = 'hour'
            for i in range(times):
                str_i = str(i)
                str_hour = str0 + str_i
                if str_hour in load_dict['data'].keys():
                    hour = load_dict['data'][str_hour]
                    hour = np.array(hour)
                    for m in range(length):
                        for n in range(width):
                            all_data[m][n][i + j * times] = hour[m][n]
                            count_data[m][n] = hour[m][n] + count_data[m][n]

    return all_data, count_data


def read_json_one_row(base_path, row, width, times=24):
    """
    读数据 np.shape = (1, 45, 1008)
    :param base_path: 文件根目录
    :param row: 行
    :param width: 一行的数据数量 45
    :param times: 24
    :return:
    """
    # base_path = './bock_count_json'
    file_list = os.listdir(base_path)  # 获取根目录下json文件
    days = len(file_list)  # 一共有多少天
    all_data = np.zeros((1, width, times * days))  # 3维矩阵
    count_data = np.zeros((1, width))  # 2维矩阵 42天内每个单元格总和

    for j in range(len(file_list)):

        path = base_path + '/' + file_list[j]
        with open(path) as f:
            load_dict = json.load(f)
            str0 = 'hour'
            for i in range(times):
                str_i = str(i)
                str_hour = str0 + str_i
                if str_hour in load_dict['data'].keys():
                    hour = load_dict['data'][str_hour]
                    hour = np.array(hour)
                    for n in range(width):
                        all_data[0][n][i + j * times] = hour[row - 1][n]
                        count_data[0][n] = hour[row - 1][n] + count_data[0][n]

    return all_data, count_data
